//!
//! Copyright (c) 2024-2999 北京心月狐科技有限公司 All rights reserved.
//!
//! https://www.mxxshop.com
//!
//! Licensed 并不是自由软件，未经许可不能去掉 MxxShop 相关版权
//!
//! 版权所有，侵权必究！
//!

use std::{fs, path};
use actix_multipart::{
    form::{
        MultipartForm,
    },
};
use crate::core::errors::error::{Result};
use actix_session::Session;
use actix_web::HttpResponse;
use crate::core::web::base_controller::{get_user_id};
use crate::core::web::response::ResVO;
use crate::modules::upload::entity::attach_entity::{AvatarForm, ImageForm};
use crate::modules::upload::service::attach_service;
use crate::modules::upload::service::attach_service::{upload_path, upload_url};
use crate::modules::user::service::user_service;
use crate::utils::{encryption_utils};

// 上传图片
pub async fn upload_image(session: Session, form: MultipartForm<ImageForm>, ) -> HttpResponse {
    let form = form.into_inner();

    return attach_service::upload_image("article".to_string(), form).await;
}


// 上传头像
pub async fn upload_avatar(session: Session, form: MultipartForm<AvatarForm>, ) -> Result<HttpResponse> {
    let user_id = get_user_id(session).unwrap_or_default();
    let user = user_service::get_by_id(&Some(user_id)).await?;
    let form = form.into_inner();

    let file_name = form.file.file_name.unwrap_or_else(|| "".to_string());

    if file_name.as_str() == "" {
        return Ok(HttpResponse::Ok().json(ResVO::<String>::error_msg("上传失败".to_string())));
    }

    let avatar_dir = upload_path("/avatar/".to_string(), "".to_string());

    if !path::Path::new(avatar_dir.as_str()).exists() {
        fs::create_dir_all(avatar_dir.as_str())?;
    }

    let id: u64 = user_id;
    

    let name = encryption_utils::sha1(id.to_string().as_str());

    let ext = attach_service::get_extension(file_name.clone().as_str());
    let name = format!("{}.{}", name.clone(), ext);
    let path = upload_path("avatar".to_string(), name.clone());
    let url = upload_url("avatar".to_string(), name.clone());

    if let Err(err) = fs::copy(&form.file.file.path(), &path) {
        eprintln!("上传失败: {:?}", err);
        return Ok(HttpResponse::Ok().json(ResVO::<String>::error_msg("上传失败".to_string())));
    }

    Ok(HttpResponse::Ok().json(ResVO::<String>::ok_msg("上传成功".to_string())))
}